<?php
// $Id: table_shop.php 464 2012-07-12 03:51:51Z tomqin@gmail.com $

class Table_Shop_Module{
    public $user = null;

    const SHOP_TYPE_WAIMAI = 1;
    const SHOP_TYPE_HOTEL  = 2;

    private $isadmin   = false;
    private $userid    = 0;

    public function __construct($user = null){
        $this->user = $user;
        if(!is_null($this->user) && $this->user){
            $this->userid  = $this->user->uid;
            $this->isadmin = ($this->user->status == USER_ADMIN);
        }else{
            $this->userid  = 0;
            $this->isadmin = false;
        }
    }

    public function check_user_right($shop_id){
        if($this->user->status == USER_ADMIN){
            return true;
        }elseif($this->user->status == USER_BUSINESS){
            $uid = $this->userid;
            $shop_id = intval($shop_id);
            return Db::getFirst("SELECT shop_id FROM `biz_shop` WHERE admin_uid = '$uid' AND shop_id = '$shop_id'");
        }else{
            return false;
        }
    }

    public function get_data($shop_id, $sample = false){
        $shop_id = intval($shop_id);
        if($sample){
            $sql  = "SELECT s.* FROM `biz_shop` s ";
            $sql .= "WHERE s.shop_id = '{$shop_id}' ";
        }else{
            $sql  = "SELECT se.*, s.* FROM `biz_shop` s ";
            $sql .= "LEFT JOIN `biz_shop_extra` se ON se.shop_id = s.shop_id ";
            $sql .= "WHERE s.shop_id = '{$shop_id}' ";
        }
        if(!$this->isadmin){
            $sql .= "AND s.admin_uid = '{$this->userid}' ";
        }
        return Db::getRow($sql);
    }

    public function search(&$search, &$order, &$page, &$total, $eachpage = 10){
        if(!isset($order['ordnum'])) $order['ordnum'] = 'desc';
        if(!$this->isadmin && $this->userid){
            $search['admin_uid'] = $this->userid;
        }

        $where = ' city_id = '.App::getCityId();
        $ordby = '';
        $_search = $_order = array();
        $key_equal = array('shop_id', 'shop_type', 'zone_id', 'subzone_id', 'city_id', 'admin_uid');
        $key_order = array('shop_id', 'shop_type', 'zone_id', 'subzone_id', 'create_dt', 'update_dt', 'ordnum');

        foreach($key_equal as $key){
            if(isset($search[$key]) && $search[$key]){
                $_search[$key]  = intval($search[$key]);
                $where .= " AND `{$key}` = '" .Db::escapeString($_search[$key]). "'";
            }
        }
        if(isset($search['q']) && $search['q']){
            $q = Db::escapeString(trim($search['q']));
            $_search['q'] = urlencode($search['q']);
            if(is_numeric($q)){
                $where .= " AND (`shop_id` = '{$q}' OR `telphone` Like '%{$q}%')";
            }elseif(strlen($q) > 3){
                $where .= " AND (`name` Like '%{$q}%' OR `alias_name` Like '%{$q}%' OR `address` Like '%{$q}%')";
            }
        }
        $search = $_search;

        foreach($order as $key => $ord){
            if(in_array($key, $key_order)){
                $_order[]  = "`{$key}` " . (strtolower($ord) == 'desc' ? 'DESC' : 'ASC');
            }else{
                unset($order[$key]);
            }
        }

        $total = Db::getFirst("select count(shop_id) from `biz_shop` where {$where}");
        if($total > 0){
            if(count($_order)){
                $ordby = ' ORDER BY '. join(',', $_order);
            }
            $page = real_page($page, $total, $eachpage);
            $offset = ($page - 1) * $eachpage;
            $sql = "select * from `biz_shop` where {$where} {$ordby} Limit {$offset}, {$eachpage}";
            return Db::getAll($sql);
        }else{
            $page = 1;
        }
        return false;
    }

    public function delete($shop_id){
        $shop_id = intval($shop_id);
        $sql = "DELETE FROM `biz_shop` WHERE shop_id = `$shop_id`";
        if($this->isadmin){
            $sql .= " AND admin_uid = '{$this->userid}'";
        }
        Db::query($sql);
        return Db::affectedRows();
    }

    public function insert(array $post){
        $table   = 'biz_shop';
        $shop_id = Db::insert($table, $this->get_fields($table, $post, 'insert'));

        $post['shop_id'] = $shop_id;

        $table   = 'biz_shop_extra';
        $result  = Db::insert($table, $this->get_fields($table, $post, 'insert'));
    }

    public function update($shop_id, array $post){
        $shop_id = intval($shop_id);

        $table   = 'biz_shop';
        Db::update(
            $table,
            $this->get_fields($table, $post, 'update'),
            array('shop_id' => $shop_id)
        );

        $table   = 'biz_shop_extra';
        Db::update(
            $table,
            $this->get_fields($table, $post, 'update'),
            $this->isadmin ? array('shop_id' => $shop_id) : array('shop_id' => $shop_id, 'admin_uid' => $this->userid)
        );

        return true;
    }

    public function sort(array $array){
        $sql = 'UPDATE `biz_shop` SET ordnum = ? WHERE shop_id = ?';
        if(!$this->isadmin){
            $sql .= " AND admin_uid = '{$this->userid}'";
        }
        $stmt = Db::prepare($sql);
        $stmt->bind_param('ii', $ordnum, $shop_id);
        foreach($array as $shop_id => $ordnum){
            $stmt->execute();
        }
    }

    public function update_list_data($shop_id, $shop_type){

        if($shop_type == self::SHOP_TYPE_WAIMAI){
            $data = Db::getRow("SELECT `delivery_time`, `delivery_desc` FROM `biz_waimai` WHERE shop_id = '$shop_id'");
        }elseif($shop_type == self::SHOP_TYPE_HOTEL){
            $data = Db::getRow("SELECT `price`, `person`, `table`, `tags` FROM `biz_hotel` WHERE shop_id = '$shop_id'");
            $data['halls'] = Db::getFirst("SELECT COUNT(*) FROM `biz_hotel_hall` WHERE shop_id = '$shop_id'");
            $data['menus'] = Db::getFirst("SELECT COUNT(*) FROM `biz_hotel_menu` WHERE shop_id = '$shop_id'");
        }else{
            $data = array();
        }
        Db::update('biz_shop', array('list_data' => serialize($data)), array('shop_id'=> $shop_id));
    }

    public function get_fields($table, array $post, $type){
        $table = "{$table}_fields";
        return $this->$table($post, $type);
    }

    private function biz_shop_fields(array $post, $type){
        $data = array(
            'city_id'    => array_get_int($post, 'city_id'),
            'shop_type'  => array_get_int($post, 'shop_type'),
            'zone_id'    => array_get_int($post, 'zone_id'),
            'subzone_id' => array_get_int($post, 'subzone_id'),
            'name'       => str_replace(array('(', ')'), array('（', '）'), array_get_string($post, 'name')),
            'alias_name' => array_get_string($post, 'alias_name'),
            'address'    => array_get_string($post, 'address'),
            'telphone'   => array_get_string($post, 'telphone'),
            //'mobile'     => array_get_string($post, 'mobile'),
            'topic'      => array_get_string($post, 'topic'),
            'worktime'   => array_get_string($post, 'worktime'),
            'traffic'    => array_get_string($post, 'traffic'),
            'longitude'  => array_get_double($post, 'longitude'),
            'latitude'   => array_get_double($post, 'latitude'),
            'status'     => array_get_int($post, 'status'),
            'star'       => array_get_int($post, 'star'),
            'views'      => array_get_int($post, 'views'),
            'likes'      => array_get_int($post, 'likes'),
            'picture'    => array_get_string($post, 'picture'),
            'call_number'=> array_get_string($post, 'call_number'),
            'sms_number' => array_get_string($post, 'sms_number'),
            'tags'       => array_get_string($post, 'tags'),
            'admin_uid'  => array_get_int($post, 'admin_uid'),
            'create_dt'  => date('Y-m-d H:i:s', TIMESTAMP),
            'create_uid' => $this->user->uid,
            'update_dt'  => date('Y-m-d H:i:s', TIMESTAMP),
            'update_uid' => $this->user->uid,
        );

        if($type == 'update'){
            if($this->isadmin){
                $data  = array_drop_key($data, array('city_id', 'shop_type', 'list_data'));
            }else{
                $data  = array_drop_key($data, array('city_id', 'shop_type', 'list_data', 'call_number',  'status', 'star', 'views', 'likes', 'admin_uid', 'create_dt', 'create_uid'));
            }
        }
        return $data;
    }

    public function biz_shop_extra_fields(array $post, $type){
        $data = array(
            'shop_id'         => array_get_int($post, 'shop_id'),
            'seo_title'       => array_get_string($post, 'seo_title'),
            'seo_keywords'    => array_get_string($post, 'seo_keywords'),
            'seo_description' => array_get_string($post, 'seo_description'),
            'contact'         => array_get_string($post, 'contact'),
            'mobile'          => array_get_string($post, 'mobile'),
            'header_image'    => array_get_string($post, 'header_image'),
            'header_color'    => array_get_string($post, 'header_color'),
            'memo'            => array_get_string($post, 'memo'),
        );
        if($type == 'update'){
            if($this->isadmin == USER_ADMIN){
                $data = array_drop_key($data, array('shop_id'));
            }else{
                $data = array_drop_key($data, array('shop_id', 'memo'));
            }
        }
        return $data;
    }
}
?>